package com.hnx.admin.system.service.impl;

import com.google.code.kaptcha.Producer;
import com.hnx.admin.captcha.api.CaptchaCacheAPI;
import com.hnx.admin.config.AppConfig;
import com.hnx.admin.redis.RedisCache;
import com.hnx.admin.system.service.CaptchaService;
import com.hnx.admin.utils.Base64;
import com.hnx.admin.utils.IdUtil;
import com.hnx.admin.web.json.ResultJson;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/5/26   10:04:40 
描   述：
*/
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService, CaptchaCacheAPI {
    private final Producer producer;
    private final AppConfig appConfig;
    private final RedisCache redisCache;
    @Override
    public ResultJson getCode(HttpServletResponse response) {
        String uuid = IdUtil.simpleUUID();
        String verifyKey = captchaKey(uuid);
        String captchaType = appConfig.getCaptchaType();
        String capText = producer.createText();
        String code = capText;
        String capStr = capText;
        if("math".equals(captchaType)){
           capStr = capText.substring(0, capText.lastIndexOf("@"));
           code = capText.substring(capText.lastIndexOf("@") + 1);
        }
        BufferedImage image = producer.createImage(capStr);
        redisCache.setCacheObject(verifyKey, code, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return ResultJson.fail(e.getMessage());
        }
        return ResultJson.success().add("uuid", uuid).add("img", Base64.encode(os.toByteArray()));
    }
}
